/*
 * Copyright (c) 2006-2018, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2018-10-30     SummerGift   change to new framework
 * 2019-01-24     Mxf          GD32E10X change to new framework
 */
 
#include "board.h"
#include "drv_usart.h"
#include "drv_config.h"

#ifdef RT_USING_SERIAL

#define DRV_DEBUG
#define LOG_TAG             "drv.usart"
#include <drv_log.h>

#if !defined(BSP_USING_UART1) && !defined(BSP_USING_UART2) && !defined(BSP_USING_UART3) && !defined(BSP_USING_UART4) && !defined(BSP_USING_UART5)
#error "Please define at least one BSP_USING_UARTx"
/* this driver can be disabled at menuconfig → RT-Thread Components → Device Drivers */
#endif

#ifdef RT_SERIAL_USING_DMA
static void uart_dma_config(struct rt_serial_device *serial);
#endif

enum
{
#ifdef BSP_USING_UART1
    UART1_INDEX,
#endif    
#ifdef BSP_USING_UART2
    UART2_INDEX,
#endif
#ifdef BSP_USING_UART3
    UART3_INDEX,
#endif
#ifdef BSP_USING_UART4
    UART4_INDEX,
#endif
#ifdef BSP_USING_UART5
    UART5_INDEX,
#endif
};

static struct uart_config uart_config[] =
{
#ifdef BSP_USING_UART1
        UART1_CONFIG,
#endif    
#ifdef BSP_USING_UART2
        UART2_CONFIG,
#endif
#ifdef BSP_USING_UART3
        UART3_CONFIG,
#endif
#ifdef BSP_USING_UART4
        UART4_CONFIG,
#endif
#ifdef BSP_USING_UART5
        UART5_CONFIG,
#endif
};

static struct uart_driver uart_obj[sizeof(uart_config) / sizeof(uart_config[0])] = {0};

static rt_err_t uart_configure(struct rt_serial_device *serial, struct serial_configure *cfg)
{
    struct uart_driver *uart_drv;
    RT_ASSERT(serial != RT_NULL);
    RT_ASSERT(cfg != RT_NULL);
    uart_drv = (struct uart_driver *)serial->parent.user_data;
    RT_ASSERT(uart_drv != RT_NULL);
    
    uart_drv->init.USART_BaudRate            = cfg->baud_rate;
    uart_drv->init.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    uart_drv->init.USART_Mode                = USART_Mode_Tx | USART_Mode_Rx;
    
    switch (cfg->data_bits)
    {
    case DATA_BITS_8:
        uart_drv->init.USART_WordLength = USART_WordLength_8b;
        break;
    case DATA_BITS_9:
        uart_drv->init.USART_WordLength = USART_WordLength_9b;
        break;
    default:
        uart_drv->init.USART_WordLength = USART_WordLength_8b;
        break;
    }
    switch (cfg->stop_bits)
    {
    case STOP_BITS_1:
        uart_drv->init.USART_StopBits   = USART_StopBits_1;
        break;
    case STOP_BITS_2:
        uart_drv->init.USART_StopBits   = USART_StopBits_2;
        break;
    default:
        uart_drv->init.USART_StopBits   = USART_StopBits_1;
        break;
    }
    switch (cfg->parity)
    {
    case PARITY_NONE:
        uart_drv->init.USART_Parity     = USART_Parity_No;
        break;
    case PARITY_ODD:
        uart_drv->init.USART_Parity     = USART_Parity_Odd;
        break;
    case PARITY_EVEN:
        uart_drv->init.USART_Parity     = USART_Parity_Even;
        break;
    default:
        uart_drv->init.USART_Parity     = USART_Parity_No;
        break;
    }

    uart_msp_init(uart_drv->config->periph);
    USART_Init(uart_drv->config->periph,&uart_drv->init);
    USART_Cmd(uart_drv->config->periph,ENABLE);
    
    return RT_EOK;
}

static rt_err_t uart_control(struct rt_serial_device *serial, int cmd, void *arg)
{
    struct uart_driver *uart_drv;
#ifdef RT_SERIAL_USING_DMA
    rt_ubase_t ctrl_arg = (rt_ubase_t)arg;
#endif
    
    RT_ASSERT(serial != RT_NULL);
    uart_drv = (struct uart_driver *)serial->parent.user_data;
    RT_ASSERT(uart_drv != RT_NULL);

    switch (cmd)
    {
    /* disable interrupt */
    case RT_DEVICE_CTRL_CLR_INT:
        /* disable rx irq */
        NVIC_DisableIRQ(uart_drv->config->irq_type);
        /* disable interrupt */
        USART_INTConfig(uart_drv->config->periph, USART_INT_RDNE ,DISABLE);
        break;
    /* enable interrupt */
    case RT_DEVICE_CTRL_SET_INT:
        /* enable rx irq */
        NVIC_EnableIRQ(uart_drv->config->irq_type);
        /* enable interrupt */
        USART_INTConfig(uart_drv->config->periph, USART_INT_RDNE ,ENABLE);
        break;

#ifdef RT_SERIAL_USING_DMA
    case RT_DEVICE_CTRL_CONFIG:
        if (ctrl_arg == RT_DEVICE_FLAG_DMA_RX)
        {
            uart_dma_config(serial);
        }
        break;
#endif
    }
    return RT_EOK;
}

static int uart_putc(struct rt_serial_device *serial, char c)
{
    struct uart_driver *uart_drv;
    RT_ASSERT(serial != RT_NULL);

    uart_drv = (struct uart_driver *)serial->parent.user_data;
    /* for AT32 clear TC flag : 
  *     read a read operation to
  *     USART_SR register (USART_GetFlagStatus()) followed by a write operation
  *     to USART_DR register (USART_SendData())*/
//    USART_GetFlagStatus(uart_drv->config->periph, USART_FLAG_TRAC);

    USART_SendData(uart_drv->config->periph,c); //send data
    
    while (USART_GetFlagStatus(uart_drv->config->periph, USART_FLAG_TRAC) == RESET);
    return 1;
}

static int uart_getc(struct rt_serial_device *serial)
{
    int ch;
    struct uart_driver *uart_drv;
    RT_ASSERT(serial != RT_NULL);
    uart_drv = (struct uart_driver *)serial->parent.user_data;
    RT_ASSERT(uart_drv != RT_NULL);

    ch = -1;
    if (USART_GetFlagStatus(uart_drv->config->periph, USART_FLAG_RDNE) != RESET)
    {
        ch = USART_ReceiveData(uart_drv->config->periph);
    }
    return ch;
}

static const struct rt_uart_ops uart_ops =
{
    .configure = uart_configure,
    .control = uart_control,
    .putc = uart_putc,
    .getc = uart_getc,
};

/**
 * Uart common interrupt process. This need add to uart ISR.
 *
 * @param serial serial device
 */
static void uart_isr(struct rt_serial_device *serial)
{
    struct uart_driver *uart_drv;
#ifdef RT_SERIAL_USING_DMA
    rt_size_t recv_total_index, recv_len;
    rt_base_t level;
#endif
    
    RT_ASSERT(serial != RT_NULL);

    uart_drv = (struct uart_driver *) serial->parent.user_data;
    RT_ASSERT(uart_drv != RT_NULL);

    /* UART in mode Receiver -------------------------------------------------*/
    if ((USART_GetFlagStatus(uart_drv->config->periph, USART_FLAG_RDNE) != RESET) &&
        (USART_GetITStatus(uart_drv->config->periph, USART_INT_RDNE) != RESET))
    {
        rt_hw_serial_isr(serial, RT_SERIAL_EVENT_RX_IND);
    }
#ifdef RT_SERIAL_USING_DMA
    else if ((uart_drv->uart_dma_flag) && (USART_GetFlagStatus(uart_drv->config->periph, USART_FLAG_IDLEF) != RESET) &&
             (USART_GetITStatus(uart_drv->config->periph, USART_INT_IDLEF) != RESET))
    {
        level = rt_hw_interrupt_disable();
        recv_total_index = serial->config.bufsz - DMA_GetCurrDataCounter(uart_drv->config->dma_rx->channel);
        recv_len = recv_total_index - uart_drv->dma.last_index;
        uart_drv->dma.last_index = recv_total_index;
        rt_hw_interrupt_enable(level);

        if (recv_len)
        {
            rt_hw_serial_isr(serial, RT_SERIAL_EVENT_RX_DMADONE | (recv_len << 8));
        }
        
        //clear IDLE flag
        USART_GetFlagStatus(uart_drv->config->periph,USART_FLAG_IDLEF); 
        USART_ReceiveData(uart_drv->config->periph);
    }
#endif
    else
    {
        if (USART_GetFlagStatus(uart_drv->config->periph, USART_FLAG_ORERR) != RESET) //soft ware read USART_STAT0，then read USART_DATA clear this bit
        {
            USART_ReceiveData(uart_drv->config->periph);
        }
        if (USART_GetFlagStatus(uart_drv->config->periph, USART_FLAG_NERR) != RESET) //soft ware read USART_STAT0，then read USART_DATA clear this bit
        {
            USART_ReceiveData(uart_drv->config->periph);
        }
        if (USART_GetFlagStatus(uart_drv->config->periph, USART_FLAG_FERR) != RESET) //soft ware read USART_STAT0，then read USART_DATA clear this bit
        {
            USART_ReceiveData(uart_drv->config->periph);
        }
        if (USART_GetFlagStatus(uart_drv->config->periph, USART_FLAG_PERR) != RESET) //soft ware read USART_STAT0，then read USART_DATA clear this bit
        {
            USART_ReceiveData(uart_drv->config->periph);
        }
        if (USART_GetFlagStatus(uart_drv->config->periph, USART_FLAG_LBDF) != RESET) //soft chear this bit
        {
            USART_ClearFlag(uart_drv->config->periph,USART_FLAG_LBDF);
        }
        if (USART_GetFlagStatus(uart_drv->config->periph, USART_FLAG_CTSF) != RESET)//soft chear this bit
        {
            USART_ClearFlag(uart_drv->config->periph,USART_FLAG_CTSF);
        }
        if (USART_GetFlagStatus(uart_drv->config->periph, USART_FLAG_RDNE) != RESET) //RXNE flag can be also cleared by a read to the USART_DR register (USART_ReceiveData()).
        {
            USART_ClearFlag(uart_drv->config->periph,USART_FLAG_RDNE);
        }
    }
}

#ifdef RT_SERIAL_USING_DMA
void dma_rx_done_isr(struct rt_serial_device *serial)
{
    struct uart_driver *uart_drv;
    rt_size_t recv_len;
    rt_base_t level;

    uart_drv = (struct uart_driver *) serial->parent.user_data;
    serial = &uart_drv->serial;

    level = rt_hw_interrupt_disable();

    recv_len = serial->config.bufsz - uart_drv->dma.last_index;
    uart_drv->dma.last_index = 0;

    rt_hw_interrupt_enable(level);
    if (recv_len)
    {
        rt_hw_serial_isr(serial, RT_SERIAL_EVENT_RX_DMADONE | (recv_len << 8));
    }
    
    /* clear transfer complete flag */ 
    uart_drv->config->dma_rx->dma_periph->ICLR |= (uint32_t)(DMA_INTF_TC << ((uart_drv->config->dma_rx->DMAx_INTC_shift-1) * 4U));
}
#endif


#if defined(BSP_USING_UART1)
void USART1_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    uart_isr(&(uart_obj[UART1_INDEX].serial));
    
    /* leave interrupt */
    rt_interrupt_leave();
}
#if defined(RT_SERIAL_USING_DMA) && defined(BSP_UART1_RX_USING_DMA)
void USART1_DMA_RX_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    dma_rx_done_isr(&(uart_obj[UART1_INDEX].serial));
    
    /* leave interrupt */
    rt_interrupt_leave();
}
#endif /* defined(RT_SERIAL_USING_DMA) && defined(BSP_UART1_RX_USING_DMA) */
#endif /* BSP_USING_UART1*/

#if defined(BSP_USING_UART2)
void USART2_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    uart_isr(&(uart_obj[UART2_INDEX].serial));
    
    /* leave interrupt */
    rt_interrupt_leave();
}
#if defined(RT_SERIAL_USING_DMA) && defined(BSP_UART2_RX_USING_DMA)
void USART2_DMA_RX_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    dma_rx_done_isr(&(uart_obj[UART2_INDEX].serial));

    /* leave interrupt */
    rt_interrupt_leave();
}
#endif /* defined(RT_SERIAL_USING_DMA) && defined(BSP_UART2_RX_USING_DMA) */
#endif /* BSP_USING_UART2 */

#if defined(BSP_USING_UART3)
void USART3_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    uart_isr(&(uart_obj[UART3_INDEX].serial));

    /* leave interrupt */
    rt_interrupt_leave();
}
#if defined(RT_SERIAL_USING_DMA) && defined(BSP_UART3_RX_USING_DMA)
void UART3_DMA_RX_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    dma_rx_done_isr(&(uart_obj[UART3_INDEX].serial));

    /* leave interrupt */
    rt_interrupt_leave();
}
#endif /* defined(RT_SERIAL_USING_DMA) && defined(BSP_UART3_RX_USING_DMA) */
#endif /* BSP_USING_UART3 */

#if defined(BSP_USING_UART4)
void UART4_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    uart_isr(&(uart_obj[UART4_INDEX].serial));
    
    /* leave interrupt */
    rt_interrupt_leave();
}
#if defined(RT_SERIAL_USING_DMA) && defined(BSP_UART4_RX_USING_DMA)
void UART4_DMA_RX_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    dma_rx_done_isr(&(uart_obj[UART4_INDEX].serial));

    /* leave interrupt */
    rt_interrupt_leave();
}
#endif /* defined(BSP_UART_USING_DMA_RX) && defined(BSP_UART4_RX_USING_DMA) */
#endif /* BSP_USING_UART4*/

#if defined(BSP_USING_UART5)
void UART5_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    uart_isr(&(uart_obj[UART5_INDEX].serial));
    
    /* leave interrupt */
    rt_interrupt_leave();
}
#if defined(RT_SERIAL_USING_DMA) && defined(BSP_UART5_RX_USING_DMA)
void UART5_DMA_RX_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    HAL_DMA_IRQHandler(&uart_obj[UART5_INDEX].dma.handle);

    /* leave interrupt */
    rt_interrupt_leave();
}
#endif /* defined(BSP_UART_USING_DMA_RX) && defined(BSP_UART5_RX_USING_DMA) */
#endif /* BSP_USING_UART5*/

#ifdef RT_SERIAL_USING_DMA
static void uart_dma_config(struct rt_serial_device *serial)
{
    NVIC_InitType NVIC_InitStruct;
    RT_ASSERT(serial != RT_NULL);
    struct uart_driver *uart_drv = (struct uart_driver *)serial->parent.user_data;
    RT_ASSERT(uart_drv != RT_NULL);
    struct rt_serial_rx_fifo *rx_fifo;
    
    LOG_D("%s dma config start", uart_drv->config->name);

    
    rx_fifo = (struct rt_serial_rx_fifo *)serial->serial_rx;
    
    /* DMA clock config */
    if(uart_drv->config->dma_rx->dma_periph == DMA1)
    {
        RCC_AHBPeriphClockCmd(RCC_AHBPERIPH_DMA1,ENABLE);
    }
    else if(uart_drv->config->dma_rx->dma_periph == DMA2)
    {
        RCC_AHBPeriphClockCmd(RCC_AHBPERIPH_DMA2,ENABLE);
    }
    
    /* DMA init config */
    DMA_Reset(uart_drv->config->dma_rx->channel);
    DMA_DefaultInitParaConfig(&uart_drv->dma.init);    
    
    uart_drv->dma.init.DMA_Direction    = DMA_DIR_PERIPHERALSRC;
    uart_drv->dma.init.DMA_PeripheralInc   = DMA_PERIPHERALINC_DISABLE;
    uart_drv->dma.init.DMA_MemoryInc   = DMA_MEMORYINC_ENABLE;
    uart_drv->dma.init.DMA_PeripheralDataWidth = DMA_PERIPHERALDATAWIDTH_BYTE;
    uart_drv->dma.init.DMA_MemoryDataWidth = DMA_MEMORYDATAWIDTH_BYTE;
    uart_drv->dma.init.DMA_Priority     = DMA_PRIORITY_MEDIUM;
    
    uart_drv->dma.init.DMA_PeripheralBaseAddr  = (rt_uint32_t)(&uart_drv->config->periph->DT); //USART_DATA regiest
    uart_drv->dma.init.DMA_MemoryBaseAddr  = (rt_uint32_t)rx_fifo->buffer;
    uart_drv->dma.init.DMA_BufferSize       = serial->config.bufsz;
    
    uart_drv->dma.init.DMA_Mode = DMA_MODE_CIRCULAR;    
    uart_drv->dma.init.DMA_MTOM = DMA_MEMTOMEM_DISABLE;

    DMA_Init(uart_drv->config->dma_rx->channel ,&uart_drv->dma.init); 
    
    /* enable nvic uart interrupt */
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 1;
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStruct.NVIC_IRQChannel = uart_drv->config->irq_type;
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStruct);
    /* enable nvic dma interrupt */
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStruct.NVIC_IRQChannel = uart_drv->config->dma_rx->dma_irq;
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStruct);
    /* enable uart idle interrupt */
    USART_INTConfig(uart_drv->config->periph,USART_INT_IDLEF,ENABLE);
    USART_DMACmd(uart_drv->config->periph,USART_DMAReq_Rx,ENABLE);
    /* enable dma channel */
    DMA_INTConfig(uart_drv->config->dma_rx->channel,DMA_INT_TC,ENABLE);
    DMA_ChannelEnable(uart_drv->config->dma_rx->channel,ENABLE);
    
    LOG_D("%s dma RX instance: %x", uart_drv->config->name, uart_drv->config->dma_rx->dma_periph);
    LOG_D("%s dma config done", uart_drv->config->name);
}
#endif  /* RT_SERIAL_USING_DMA */

static void uart_get_dma_config(void)
{
#ifdef BSP_UART1_RX_USING_DMA
    uart_obj[UART1_INDEX].uart_dma_flag = 1;
    static struct dma_config uart1_dma_rx = UART1_DMA_CONFIG;
    uart_config[UART1_INDEX].dma_rx = &uart1_dma_rx;
#endif    
#ifdef BSP_UART2_RX_USING_DMA
    uart_obj[UART2_INDEX].uart_dma_flag = 1;
    static struct dma_config uart2_dma_rx = UART2_DMA_CONFIG;
    uart_config[UART2_INDEX].dma_rx = &uart2_dma_rx;
#endif
#ifdef BSP_UART3_RX_USING_DMA
    uart_obj[UART3_INDEX].uart_dma_flag = 1;
    static struct dma_config uart3_dma_rx = UART3_DMA_CONFIG;
    uart_config[UART3_INDEX].dma_rx = &uart3_dma_rx;
#endif
#ifdef BSP_UART4_RX_USING_DMA
    uart_obj[UART4_INDEX].uart_dma_flag = 1;
    static struct dma_config uart4_dma_rx = UART4_DMA_CONFIG;
    uart_config[UART4_INDEX].dma_rx = &uart4_dma_rx;
#endif
#ifdef BSP_UART5_RX_USING_DMA
    uart_obj[UART5_INDEX].uart_dma_flag = 1;
    static struct dma_config uart5_dma_rx = UART5_DMA_CONFIG;
    uart_config[UART5_INDEX].dma_rx = &uart5_dma_rx;
#endif
}

int rt_hw_usart_init(void)
{
    rt_size_t obj_num = sizeof(uart_obj) / sizeof(struct uart_driver);
    struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT;
    rt_err_t result = 0;
    
    uart_get_dma_config();
    
    for (int i = 0; i < obj_num; i++)
    {
        uart_obj[i].config = &uart_config[i];
        uart_obj[i].serial.ops    = &uart_ops;
        uart_obj[i].serial.config = config;
        
#if defined(RT_SERIAL_USING_DMA)     
        if(uart_obj[i].uart_dma_flag)
        {
            /* register UART device */
            result = rt_hw_serial_register(&uart_obj[i].serial,uart_obj[i].config->name,
                                           RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_DMA_RX  | RT_DEVICE_FLAG_INT_RX
                                           ,&uart_obj[i]);            
        }
        else
#endif       
        {
            /* register UART device */
            result = rt_hw_serial_register(&uart_obj[i].serial,uart_obj[i].config->name,
                                           RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX
                                           ,&uart_obj[i]);
        }
        RT_ASSERT(result == RT_EOK);
    }

    return result;
}
INIT_BOARD_EXPORT(rt_hw_usart_init);

#endif /* RT_USING_SERIAL */
